var httpUtil = require('../../utils/httpUtil.js');
var openid = wx.getStorageSync("openId")
// pages/me/me.js
Page({

  /**
   * 页面的初始数据
   */

  data: {
    hidden: false, //加载
    outline: false, //有无网络
    list: [],
    show: false,
    newsType: 1,
    currentPage: 1,
    countDownMinute: '',
    countDownSecond: '00',
    pagecount:'',
    noData:false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success(res) {
              console.log(res.userInfo)
            }
          })
        }
      }
    })
  },

  bindGetUserInfo(e) {
    var that = this;
    that.setData({
      hidden:true,
    })
    var req = {
      nickname: JSON.parse(e.detail.rawData).nickName,
      headimgurl: JSON.parse(e.detail.rawData).avatarUrl,
      openid: openid,
      city: JSON.parse(e.detail.rawData).city,
      province: JSON.parse(e.detail.rawData).province,
      sex: JSON.parse(e.detail.rawData).gender
    }
    wx.request({
      url: 'https://www.tiantong369.com/crm/noworder',
      data: req,
      method: "POST",
      //头信息设置
      header: {
        'x-access-token': wx.getStorageSync("token")
      },
      success: function(res) {
        that.setData({
          hidden: false,
        })
        if (res.data.status == 200) {
          console.log(that)
          var totalSecond = res.data.data;
          that.setData({
            hidden:false,
            show: true,
            countDownMinute: e.currentTarget.dataset.time
          })
          var interval = setInterval(function() {
            // 秒数
            var second = totalSecond;
            // 分钟位
            var min = Math.floor((second) / 60);
            var minStr = min.toString();
            if (minStr.length == 1) minStr = '0' + minStr;
            // 秒位
            var sec = second - min * 60;
            var secStr = sec.toString();
            if (secStr.length == 1) secStr = '0' + secStr;
            that.setData({
              countDownMinute: minStr,
              countDownSecond: secStr,
            })
            totalSecond--;
            if (totalSecond < 0) {
              clearInterval(interval);
              wx.showToast({
                title: '体验已结束',
              });
              that.setData({
                countDownMinute: '00',
                countDownSecond: '00',
              })
            }
          }, 1000);

        }else{
          wx.showToast({
            title: '' + res.data.message+'',
            icon:'none'
          });

        }
      },
      fail: function(res) {

      }
    });



  },
  refund: function(e) {
    var that = this;
    that.setData({
      hidden: true
    })
    var req = {
      orderid: e.currentTarget.dataset.id
    }
    console.log(req)
    wx.request({
      url: 'https://www.tiantong369.com/crm/Refund',
      data: req,
      method: "POST",
      //头信息设置
      header: {
        'x-access-token': wx.getStorageSync("token")
      },
      success: function(res) {
        that.setData({
          hidden: false
        })
        if (res.data.status == 200) {
          wx.showToast({
            title: '退款成功',
          })
          
        }else{
          wx.showToast({
            title: '' + res.data.message+'',
            icon:'none'
          })
        }
      },
      fail: function(res) {

      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    //获取当前网络状态
    wx.getNetworkType({
      success: function(res) {
        // 返回网络类型, 有效值：
        // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
        if (res.networkType == 'none' || res.networkType == 'unknown') {
          that.setData({
            outline: true
          })
        } else {
          that.setData({
            outline: false,
          })
          that.getToken()
        }
      }
    })

    //监听网络状态
    wx.onNetworkStatusChange(function(res) {
      if (res.networkType == 'none' || res.networkType == 'unknown') {
        that.setData({
          outline: true
        })
      } else {
        that.setData({
          outline: false,
        })
        that.getToken()
      }
    })
  },
  close: function(e) {
    var that = this;
    that.setData({
      show: false
    })
  },
  active: function(e) {
    var that = this;
    if (e.currentTarget.dataset.id != that.data.newsType) {
      that.setData({
        newsType: e.currentTarget.dataset.id,
        list: []
      })
      if (that.data.newsType == '1') {
        that.setData({
          status: 'pay',
        })
      } else if (that.data.newsType == '2') {
        that.setData({
          status: 'unpay',
        })
      } else if (that.data.newsType == '3') {
        that.setData({
          status: '',
        })
      }
      that.login()
    }
  },
  // 获取token
  getToken: function() {
    var that = this;
    that.setData({
      hidden: true
    })
    wx.login({
      success: function(res) {
        if (res.code) {
          var req = JSON.stringify({
            code: res.code
          })
          //获取sessionKey
          wx.request({
            url: 'https://www.tiantong369.com/gettoken',
            data: req,
            method: "POST",
            //头信息设置
            header: {},
            success: function(res) {
              if (res.data.status == 200) {
                wx.setStorageSync("token", res.data.token);
                that.login()
              }
            },
            fail: function(res) {


            }
          });
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    });
  },
  //获取登录信息
  login: function() {
    var that = this;
    wx.login({
      success: function(res) {
        if (res.code) {
          var req = {
            js_code: res.code,
          }
          //获取sessionKey
          wx.request({
            url: 'https://www.tiantong369.com/crm/GetWXUserInfo/',
            data: req,
            method: "POST",
            //头信息设置
            header: {
              'x-access-token': wx.getStorageSync("token")
            },
            success: function(res) {
              wx.setStorageSync("openId", res.data.openid);
              wx.setStorageSync("sessionKey", res.data.session_key);
              var req = {
                openid: '' + res.data.openid + '',
                page: that.data.currentPage
              }
              httpUtil.post("/crm/myorder", req)
                .then(function(res) {
                  that.setData({
                    hidden: false
                  })
                  if (res.data.status == 200) {
                    var arr = [];
                    for (var i = 0; i < res.data.data.list.length; i++) {
                      arr.push(res.data.data.list[i])
                    }
                    that.setData({
                      list: arr,
                      noData:false,
                      pagecount: res.data.data.count
                    })
                    if(that.data.list.length==0){
                      that.setData({
                        noData: true
                      })
                    }
                  } else {
                    wx.showToast({
                      title: '' + res.data.err_msg + '',
                      icon: 'none',
                    })
                  }
                }).catch(function(res) {
                  console.log(res);
                });
            },
            fail: function(res) {
              wx.showToast({
                title: '获取登录信息失败，请稍后重试',
              })
              return;
            }
          });
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    var that = this;
    that.setData({
      hidden: false,
    })
    var num = that.data.currentPage;
    num++;
    that.setData({
      currentPage: num
    })
    if (that.data.pagecount < num) {
      wx.showToast({
        title: '没有更多数据了',
        icon: 'none',
        duration: 1000
      })
      return;
    }
    that.login()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
})